package com.harassment.interception.interception.sms;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.BlackList;
import com.harassment.interception.data.databases.entities.InterceptedSms;
import com.harassment.interception.data.databases.entities.WhiteList;
import com.harassment.interception.ui.fragments.setting.SettingFragment;

import java.util.Date;
import java.util.List;

public class SmsInterceptionService extends IntentService {
    private static final String TAG = "SmsInterceptionService";

    public SmsInterceptionService() {
        super("SmsInterceptionService");
    }

    public static void startService(Context context,SmsReceiver smsReceiver, Intent intent) {
        Log.d(TAG, "startService");
        Intent actionIntent = new Intent(context, SmsInterceptionService.class);
        actionIntent.putExtras(intent.getExtras());
        actionIntent.putExtra(SmsReceiver.BROADCAST_RECEIVER, smsReceiver);
        context.startService(actionIntent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent == null) {
            return;
        }
        if (!SettingFragment.isIntercept()) {
            return;
        }
        InterceptedSms[] interceptedSms = SmsInterception.getInterceptedSms(intent);
        for (InterceptedSms temp : interceptedSms) {
            if (SmsInterception.whitePattern(temp.getNumber())) {
                return;
            }
            if (SmsInterception.blackPattern(temp.getNumber())) {
                SmsReceiver receiver = (SmsReceiver) intent.getSerializableExtra(SmsReceiver.BROADCAST_RECEIVER);
                if (receiver != null) {
                    receiver.abortBroadcast();
                }
                HIDBUtil.getInterceptedSmsDao().addInterceptedSms(temp);
                return;
            }
        }
    }

}
